//
//  HMStatusListViewModel.swift
//  Weibo13
//
//  Created by apple on 16/1/22.
//  Copyright © 2016年 itheima. All rights reserved.
//  首页的数据都由当前 ViewModel 来控制,其对应的 View 是 Home 的 tableView

import UIKit

class HMStatusListViewModel: NSObject {
    
    // 保存请求回来数据的数组
    var statusArray: [HMStatus]?
    
    /// 请求首页数据
    func loadStatuses(finished: (isSuccess: Bool)->()){
        // 以下代码抽取到 HMNetworkTools 里面
//        let urlString = "https://api.weibo.com/2/statuses/friends_timeline.json"
//        let params = [
//            "access_token": HMUserAccountViewModel.sharedViewModel.accessToken!
//        ]
        let access_token = HMUserAccountViewModel.sharedViewModel.accessToken!
        HMNetworkTools.sharedTools.loadStatuses(access_token) { (response, error) -> () in
            if error != nil {
                print(error)
                // 告诉外界,当前请求失败
                finished(isSuccess: false)
                return
            }
            
            guard let responseDict = response as? [String: AnyObject] else {
                print("返回的数据不在字典类型")
                // 告诉外界,当前请求失败
                finished(isSuccess: false)
                return
            }
            
            /// 取到字典数组
            let statuses = responseDict["statuses"]! as! [[String: AnyObject]]
            
            // 遍历数组字典转模型
            
            var tempArray = [HMStatus]()
            
            for statusDict in statuses {
                let status = HMStatus(dict: statusDict)
                tempArray.append(status)
            }
            
            //赋值数据
            self.statusArray = tempArray
            print("11")
            // 告诉外界,当前请求失败
            finished(isSuccess: true)
        }
    }
}
